package com.itheima;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        test1();
        test2();

    }
    public static void test1(){
        TreeMap<Student, String> treeMap = new TreeMap<>();
        treeMap.put(new Student("小赵", 21, "深圳"), "深圳");
        treeMap.put(new Student("小钱", 22, "杭州"), "杭州");
        treeMap.put(new Student("小王", 18, "北京"), "北京");
        treeMap.put(new Student("小李", 20, "广州"), "广州");
        treeMap.put(new Student("小张", 19, "上海"), "上海");
        // 遍历TreeMap并打印键值对
        for (Map.Entry<Student, String> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + " --- " + entry.getValue());
        }
    }
    public static void test2() {
        // 创建一个TreeMap，键为Student类型，值为String类型
        TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                // 根据年龄进行排序
                return o2.getAge() - o1.getAge();
            }
        });

        // 向TreeMap中添加键值对
        treeMap.put(new Student("小赵", 21, "深圳"), "深圳");
        treeMap.put(new Student("小钱", 22, "杭州"), "杭州");
        treeMap.put(new Student("小王", 18, "北京"), "北京");
        treeMap.put(new Student("小李", 20, "广州"), "广州");
        treeMap.put(new Student("小张", 19, "上海"), "上海");
        // 遍历TreeMap并打印键值对
        for (Map.Entry<Student, String> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + " --- " + entry.getValue());
        }
    }
}
